// 路由跳转
import { useLocation } from "react-router";
import { useNavigate } from "react-router-dom";
import queryString from "query-string";
import {useMemo} from "react";

export default <
    T extends Record<any, any> = Record<any, any>,
    Query = { [K in keyof T]: string }
>(queryPipe?: (query: Query) => T) => {
    const routerLocation = useLocation();
    const routerNavigate = useNavigate();
    const queryOrigin = queryString.parse(routerLocation.search) as unknown as Query;
    const queryData = (queryPipe? queryPipe(queryOrigin) : queryOrigin) as typeof queryPipe extends undefined ? Query : T;
    const to = (path: string, query?: object) => {
        if (query) {
            const paramsString = queryString.stringify(query);
            const url = `${path}?${paramsString}`;
            routerNavigate(url);
        } else {
            const url = `${path}`;
            routerNavigate(url);
        }
    };
    const changeQuery = (query: T) => {
        to(routerLocation.pathname, query);
    };
    return {
        to,
        changeQuery,
        queryOrigin,
        query: queryData,
        routerLocation,
        routerNavigate
    };
};
